<template>
  <div class="p-10">
    <templateEdit :Fieldss="Fields" :Template="Template" :MT="MainTable" :DataSource="AllData" :Action="Action"
                  :DT="DetailTables" :alltable="alltable" :Combo="combo" :Rules="rules" :isequipment="isequipment" :ActRules="ActRules" :load="load" :Linker="Linker" :FormStyle="formStyle"
                  :isNew="Add" Types="N" ref="EditData"></templateEdit>
    <!-- <newtemplateEdit v-if="isequipment && Template.allowPcDisp===1" :typetem="typetem" :Fieldss="Fields" :Template=" Template" :MT="MainTable" :DataSource="AllData" :Action="Action"
                  :DT="DetailTables" :Combo="combo" :Rules="rules" :isequipment="isequipment" :ActRules="ActRules" :load="load" :Linker="Linker" :FormStyle="formStyle"
                  :isNew="Add" Types="N" ref="EditData" :formSet="formSet"></newtemplateEdit>
    <WaptemplateEdit v-if="!isequipment && Template.allowPcDisp===0" :Fields="Fields" :Template=" Template" :Title=" Template.templateTitle" :MT="MainTable" :DataSource="AllData" :Action="Action"
                     :DT="DetailTables" :Combo="combo" :Rules="rules" :isequipment="isequipment" :ActRules="ActRules" :load="load" :Linker="Linker"
                  :isNew="Add" ref="EditData"></WaptemplateEdit> -->
  </div>
</template>

<script>
import {onBeforeMount, onMounted, reactive, ref, toRefs} from "vue"
import {useRoute, useRouter} from 'vue-router'
import XEUtils from "xe-utils"
import {getTemplate} from "/@/api/linkoo/form/index"
import templateEdit from "/@/views/linkoo/components/templateEdit.vue"//tydayin->章华；久盛->templateEdit
import newtemplateEdit from "/@/views/linkoo/components/NewtemplateEdit.vue"
import WaptemplateEdit from "/@/views/linkoo/components/waptemplateEdit.vue"
import typeEdit from "/@/views/linkoo/components/typeEdit.vue"
import {getForm} from "../../../api/linkoo/form";
import {isMobile} from "/@/utils/other"
import {error} from "dingtalk-jsapi";
import {typeFilter,typeData} from "/@/api/form/typeEdit"
export default {
  components: {templateEdit,WaptemplateEdit,newtemplateEdit,typeEdit},
  setup(props) {
    let router = useRouter()
    const route = useRoute()
    let alltable = ref(null)
    let state = reactive({
      Fields: {},
      AllData: { StatusCode:0 },
      Template: {},
      typetem:null,
      Template1:{},
      MainTable: {},
      DetailTables: [],
      combo: {}, rules: {},
      isequipment: true,
      ActRules: {},
      Linker: {},
      Action: {},
      formStyle:{},
      formSet:null,
      Add: true,
      load: false,
      TableData: [],
      MainPage: {pageNum: 1, pageSize: 10, totalResult: 0}
    })
    let EditData = ref(null)
    onMounted(async () => {
      if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) {
        state.isequipment = false;
      } else {
        state.isequipment = true
      }
      if(XEUtils.isEmpty(route.params)){
          if(route.fullPath.includes("Print")){
          route.params.templateCode= route.fullPath.substring(route.fullPath.lastIndexOf("/")+1)
          route.params.id= 0
          state.Action['TM']="Print"
          }
      }else if (route.params.id !== '0'){
        state.Add=false
      }
      await typeData(route.params.templateCode).then((res)=>{
            if(res.code===0){
              state.typetem=res.data
            }
      })
      await getTemplate(route.params.templateCode).then( (response) => {
        alltable.value=response.data.tables
          state.MainTable = response.data.tables.filter(item => item.tableType === 0)[0]
          state.DetailTables = response.data.tables.filter(item => item.tableType === 1).map(row=>{
            row['Orders']=response.data.orders[row.tableName]

            row.TreeSum= {}
            if(row.layoutStyle.length>0){
              const tt=row.layoutStyle.split('|');
              row.layoutStyle=tt[0].split(',');
              if(tt.length>1)
              row.TreeSum=JSON.parse(tt[1]);
            } else{row.layoutStyle=[]}
            row.onSheet=row.onSheet.length>0?row.onSheet.split(','):[];
            return row
          })
          state.ActRules = BuildRules(XEUtils.orderBy((XEUtils.toArray(response.data['actRules'] || []).filter(item => item.isActive === 1)), 'runSeq'))
        XEUtils.objectEach( response.data.editRules,(items,table)=>{
          state.rules[table]={}
          XEUtils.objectEach( items,(item,field)=>{
            state.rules[table][field]=item.map(row=>{
              if(row.validator!==undefined){
                row.validator=eval(row.validator)
              }
              return row
            })
          })

        })
          state.combo = response.data.combos
          state.Linker = response.data.linker
          state.Action =XEUtils.assign(state.Action , response.data.action)
          if(state.Action.canReview==1){
            state.Action['canCreate']=1
          }
          state.Template = response.data.template
          XEUtils.arrayEach(response.data.tables, row => {
            state.Fields[row.tableName] = row.Fields
          })
        })
      if(state.Template.FormCode){
        state.formStyle= JSON.parse(state.Template.FormCode)['formData']
        state.formSet=JSON.parse(state.Template.FormCode)['formSet']
        // add1.formData['tableName']=state.MainTable.tableName
        // add1.formData['tableId']=state.MainTable.tableID
        // // state.MainTable.Fields.forEach((element,index) => {
        // //   if(element.fieldName==add1.formData.mainList[index].value){
        // //     add1.formData.mainList[index]['componentFieldName']=element.componentFieldName
        // //   }
        // // });
        // // state.DetailTables.forEach((items,index)=>{
        // //   items.Fields.forEach((element,sun)=>{
        // //     add1.formData.tableList[index].column[sun]['componentFieldName']=element.componentFieldName
        // //   })
        // // })
        // state.Template.FormCode=add1
        // state.Template1=state.Template
      }
        if (route.params.id !== '0') {
          await getForm(route.params.templateCode, route.params.id, {}).then(response => {
            state.AllData = response.data
            state.load=true
          })
          if(state.Template.allowBestFitColumns===2){
          }
        }else{
          state.load=true
        }

    })
    const getextend = (data, field) => {
      let extend = XEUtils.toStringJSON(data['Extend'] ? data['Extend'] : '{}')
      if (extend[field.fieldName] === undefined) {
        extend[field.fieldName] = data[field.fieldName]
        data['Extend'] = XEUtils.toJSONString(extend)
      }
      return XEUtils.get(extend, field.fieldName)
    }
    const BuildRules = (data) => {
      const Rules = {}, rs = ["取数", '更新', '传送','通知']
      XEUtils.arrayEach(data, row => {
        if (Rules[rs[row.ruleType - 1]] === undefined) {
          Rules[rs[row.ruleType - 1]] = []
        }
        Rules[rs[row.ruleType - 1]].push(row)
      })
      return Rules
    }
    return {
      EditData,
      ...toRefs(state)
      , getextend
      , BuildRules,alltable
    }
  }
}
</script>

<style scoped>
.p-10 {
  padding: 10px;
  background-color: rgb(255, 255, 255);
}

</style>